<template>
  <div>
    <modal
      v-model="taskModal"
      draggable
      scrollable
      width="800"
      title="创建任务"
    >
      <p
        slot="header"
        class="modalHeader"
        style="display: flex; justify-content: space-between"
      >
        <span style="margin-left: 5px">{{ modalName }}任务</span>
      </p>
      <p slot="close" class="modalHeader" @click="taskCancel">
        <CButtonClose slot="close" />
      </p>

      <Form
        ref="formCustom"
        :model="formData"
        :rules="ruleCustom"
        :label-width="120"
      >
        <div class="rowAlign1">
          <FormItem label="任务名称：" prop="taskName">
            <Input type="text" v-model="formData.taskName"></Input>
          </FormItem>
          <FormItem label="输出目录" prop="outputPath">
            <Input type="text" v-model="formData.outputPath"></Input>
            <CButton
              color="info"
              class="system-btn-style"
              style="margin-left: 10px; height: 30px"
              @click="openSelectTree"
              >...</CButton
            >
          </FormItem>
        </div>
        <div class="rowAlign">
          <FormItem label="执行频率：">
            <Select size="small" v-model="formData.frequence">
              <template v-for="item in cronList">
                <Option :value="item.value" :key="item.label">{{
                  item.label
                }}</Option>
              </template>
            </Select>
          </FormItem>
          <FormItem label="流程类型">
            <Select size="small" v-model="formData.productType">
              <template v-for="item in taskTypeList">
                <Option :value="item.value" :key="item.label">{{
                  item.label
                }}</Option>
              </template>
            </Select>
          </FormItem>
        </div>

        <div>
          <Divider>查询条件</Divider>
          <Tabs
            value="TabName1"
            size="small"
            v-model="tabValue"
            style="margin-left: 31px"
          >
            <TabPane label="行政区域" name="a" class="selectCity">
              <Form :model="selectCity" :label-width="90">
                <FormItem label="区域选择：">
                  <Cascader
                    size="small"
                    :transfer="true"
                    v-model="selectCity.city"
                    :data="cityData"
                    change-on-select
                    :load-data="loadData"
                    @on-change="handleChangeCity"
                  ></Cascader>
                </FormItem>
              </Form>
            </TabPane>
            <TabPane label="预定义区域" name="b">
              <Form :model="reserveCity" :label-width="90">
                <FormItem label="区域类型：">
                  <Select size="small" v-model="reserveCity.type" transfer>
                    <template v-for="item in areaData">
                      <Option
                        :value="item.value"
                        :key="item.label"
                        :disabled="item.disabled"
                        >{{ item.label }}</Option
                      >
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="区域名称：">
                  <Select
                    size="small"
                    transfer
                    v-model="reserveCity.name"
                    @on-change="handleChangePreRegion"
                  >
                    <template v-for="item in areaDataCom">
                      <Option :value="item.distcode" :key="item.name">{{
                        item.name
                      }}</Option>
                    </template>
                  </Select>
                </FormItem>
              </Form>
            </TabPane>
            <TabPane label="上传shp" name="d">
              <Upload
                :action="$api.dataOptimizationApi.uploadShpFile"
                :on-success="onSuccess"
                :on-error="onError"
                accept=".zip"
                style="margin-left: 10px"
              >
                <Button size="small" icon="ios-cloud-upload-outline"
                  >点击上传</Button
                >
              </Upload>
              <div
                style="
                  margin-top: 10px;
                  margin-left: 10px;
                  display: flex;
                  flex-direction: column;
                "
              >
                <span>1. 仅支持单要素的zip压缩包</span>
                <span>2. 至少包括.shp,.shx,.prj,.dbf,.sbn,.sbx文件</span>
                <span>3. WGS-84坐标系</span>
              </div>
            </TabPane>
          </Tabs>

          <div style="display: flex">
            <FormItem label="开始时间：">
              <DatePicker
                v-model="formData.startTime"
                size="small"
                type="date"
                placement="bottom-end"
                placeholder="请选择开始时间"
                format="yyyy-MM-dd"
                :options="startTimeOptions"
              ></DatePicker>
            </FormItem>

            <FormItem label="结束时间：">
              <DatePicker
                v-model="formData.endTime"
                size="small"
                type="date"
                placement="bottom-end"
                placeholder="请选择结束时间"
                format="yyyy-MM-dd"
                :options="endTimeOptions"
              ></DatePicker>
            </FormItem>
          </div>

          <FormItem label="云量(%)：">
            <div>
              <Slider
                size="small"
                v-model="formData.cloudiness"
                input-size="small"
                :min="-1"
                show-input
              >
              </Slider>
            </div>
          </FormItem>

          <FormItem label="数 据 源：">
            <Collapse>
              <template v-for="(item, index) in collapseList">
                <Panel :key="index">
                  <div
                    slot
                    style="
                      display: flex;
                      justify-content: space-between;
                      width: 100%;
                    "
                  >
                    <strong>{{ item.title }}</strong>
                    <!--标题-->
                    <!-- <div>
                  <Checkbox @on-change="changeTitle($event, item)"></Checkbox>
                </div> -->
                  </div>
                  <div slot="content">
                    <template v-for="itemChild in item.children">
                      <div
                        slot
                        style="
                          display: flex;
                          justify-content: space-between;
                          width: 100%;
                        "
                        :key="itemChild.name"
                      >
                        <strong>{{ itemChild.name }}</strong>
                        <!--卫星-->
                        <div>
                          <Checkbox
                            @on-change="changeSing($event, itemChild)"
                            :value="itemChild.checked"
                          ></Checkbox>
                        </div>
                      </div>

                      <template
                        v-for="(itemChildI, indexChildI) in itemChild.sensor"
                      >
                        <Checkbox
                          :key="indexChildI.id"
                          @on-change="changeChe($event, itemChildI, itemChild)"
                          :value="itemChildI.checked"
                          :title="itemChildI.tip"
                          >{{ itemChildI.name }}</Checkbox
                        >
                      </template>
                    </template>
                  </div>
                </Panel>
              </template>
            </Collapse>
          </FormItem>
          <FormItem label="优选规则：" style="margin-top: 10px">
            <draggable v-model="dragSortDdata" class="selectOp">
              <template v-for="item in dragSortDdata">
                <div :key="item.name">
                  <Checkbox
                    v-model="item.select"
                    v-if="
                      item.name === 'cloudpercent' ||
                      item.name === 'imagegsd' ||
                      item.name === 'orbitid'
                    "
                    >{{ item.alisaName }}</Checkbox
                  >
                  <Poptip
                    placement="bottom"
                    width="300"
                    v-if="item.name === 'scenetime'"
                    trigger="hover"
                    :transfer="true"
                  >
                    <Checkbox v-model="item.select">{{
                      item.alisaName
                    }}</Checkbox>
                    <div class="api" slot="content" v-if="false">
                      <Input
                        v-model="item.value"
                        size="small"
                        placeholder="请输入轨道号,例:2005,2006"
                      />
                    </div>
                    <div
                      class="api"
                      slot="content"
                      v-if="item.name === 'scenetime'"
                    >
                      <CheckboxGroup v-model="item.value">
                        <template v-for="item in mounths">
                          <Checkbox :label="item" :key="item + 'yue'">{{
                            item + "月"
                          }}</Checkbox>
                        </template>
                      </CheckboxGroup>
                    </div>
                  </Poptip>
                </div>
              </template>
            </draggable>
          </FormItem>
        </div>
      </Form>

      <template #footer class="footerBtns">
        <CButton color="info" class="cancel-btn" @click="taskCancel"
          >取消</CButton
        >
        <CButton color="info" class="system-btn-style" @click="taskOk"
          >确定</CButton
        >
      </template>
    </modal>
    <fileCatalog
      ref="refFileCatalogModal"
      :modalShow="fileCatalogModal"
      @closed="fileCatalogModalClose"
      @menuOk="fileCatalogModalOk"
    ></fileCatalog>
  </div>
</template>
<script>
import draggable from "vuedraggable";
import fileCatalog from "../../jobProcess/fileCatalog.vue";
import {
  collapseList,
  satelliteLinkage,
  formDataList,
} from "../../../../public/static/js/commons";
export default {
  name: "cycleOptimCommon",
  props: {
    modalShow: {
      type: Boolean,
      default: false,
    },
    modalTitle: {
      type: String,
      default: "创建",
    },
  },
  data() {
    return {
      fileCatalogModal: false,
      startTimeOptions: {},
      endTimeOptions: {},

      taskTypeList: [],
      cronList: [],
      modalName: "创建",
      taskModal: false,
      taskName: "",
      formData: {
        taskName: "",
        outputPath: "",
        taskStartTime: "", //任务的开始和结束时间和查询时间保持一致 所以任务的时间界面不显示
        taskEndTime: "",
        startTime: "",
        endTime: "",
        frequence: "",
        productType: "LEVEL5A",
        cloudiness: "",
      },

      dragSortDdata: [
        {
          alisaName: "云量优先",
          name: "cloudpercent",
          select: false,
        },
        {
          alisaName: "分辨率优先",
          name: "imagegsd",
          select: false,
        },
        {
          alisaName: "轨道优先",
          name: "orbitid",
          select: false,
          value: "",
        },
        {
          alisaName: "采集时间",
          name: "scenetime",
          select: false,
          value: [5, 6, 7, 8],
        },
      ],
      mounths: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],

      /*tab区域*/
      tabValue: "a",
      // 区域
      selectCity: {
        city: [],
      },
      cityData: [],
      //预定义区域
      reserveCity: {
        type: "",
        name: "",
      },
      areaData: [
        // {label: '行政区划', value: '-1'},
        { label: "重点区域", value: "0" },
        { label: "重点流域", value: "1" },
        { label: "陆域红线边界", value: "2", disabled: true },
        { label: "海域红线边界", value: "3", disabled: true },
        { label: "国家公园", value: "4" },
        { label: "国家级自然保护区", value: "5" },
        { label: "省级自然保护区", value: "6" },
        { label: "重点生态功能区", value: "7" },
        { label: "生态文明示范创建与两山基地", value: "8", disabled: true },
        { label: "生物多样性保护优先区", value: "9" },
        { label: "海域红线", value: "10" },
        { label: "海域", value: "11" },
      ],
      areaDataCom: [],
      // 经纬度

      ruleCustom: {
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
      },

      formDataList: formDataList,
      collapseList: JSON.parse(JSON.stringify(collapseList)),
      selectSenior: new Set(),
    };
  },
  watch: {
    modalShow: {
      handler(val) {
        this.taskModal = val;
      },
      immediate: true,
      deep: true,
    },
    modalTitle: {
      handler(val) {
        this.modalName = val;
      },
      deep: true,
      immediate: true,
    },

    "reserveCity.type": {
      handler(val) {
        let that = this;
        if (!val) return;
        this.http
          .get(this.$api.dataOptimizationApi.getOtherDistrict, { type: val })
          .then((res) => {
            if (res.data.success) {
              that.areaDataCom = res.data.data.data;
            } else {
              that.$Message.error(res.data.message);
            }
          })
          .catch((err) => {
            that.$Message.error(err.data.message);
          });
      },
    },

    "formData.endTime"() {
      const _this = this;
      this.startTimeOptions.disabledDate = function (date) {
        return date.valueOf() > new Date(_this.formData.endTime);
      };
    },

    "formData.startTime"() {
      const _this = this;
      this.endTimeOptions.disabledDate = function (date) {
        return date.valueOf() < new Date(_this.formData.startTime);
      };
    },
  },

  mounted() {
    this.getQueryArea();
    this.getTaskTypeList();
  },
  components: { draggable, fileCatalog },
  methods: {
    init(data, type) {
      this.modalType = type;
      this.selectCity.city = [];
      this.reserveCity = { type: "", name: "" };

      this.cronList = data.cronList;
      if (type === "create") {
        this.formData = {
          taskName: "",
          taskEndTime: "",
          startTime: "",
          endTime: "",
          frequence: "0 0 0 1/1 * ? ",
          cloudiness: "",
        };
        this.dealwithRules([]);

        this.dealwithSensor();
      } else {
        let obj = JSON.parse(data.taskParameter);
        this.formData.taskName = data.taskName;
        this.formData.frequence = data.crontabExpress;
        this.formData.outputPath = obj.processDir;
        this.formData.productType = obj.productType;

        this.formData.taskStartTime = obj.beginTime;
        this.formData.taskEndTime = obj.beginTime;
        this.formData.startTime = obj.beginTime;
        this.formData.endTime = obj.endTime;

        this.formData.cloudiness = obj.queryParam.fields[1].value;

        let tempRules = obj.queryParam.optimalRules;
        this.dealwithRules(tempRules);

        this.tabValue = obj.areaInfo.tag;
        if (obj.areaInfo.tag === "a") {
          this.selectCity.city = obj.areaInfo.value;
        } else if (obj.areaInfo.tag === "b") {
          this.reserveCity = obj.areaInfo.value;
        } else {
        }
        //处理数据源
        this.dealwithSensor(obj.queryParam.nodeId);
      }
    },

    // 打开选择树  文件操作
    openSelectTree() {
      let that = this;
      this.fileCatalogModal = true;
      this.$nextTick(() => {
        that.$refs.refFileCatalogModal.initFileTree(
          { type: { name: "dir" } },
          true
        );
      });
    },
    fileCatalogModalClose() {
      this.fileCatalogModal = false;
    },
    fileCatalogModalOk(data) {
      this.formData.outputPath = data;
      this.fileCatalogModal = false;
    },

    dealwithRules(tempRules) {
      if (tempRules.length != this.dragSortDdata.length) {
        this.dragSortDdata.forEach((ele) => {
          let arr = tempRules.filter((item) => ele.name === item.name);
          if (arr.length < 1) tempRules.push(ele);
        });
      }
      this.dragSortDdata = tempRules;
    },

    //处理传感器的回显
    dealwithSensor(nodeId) {
      this.collapseList.forEach((ele) => {
        ele.children.forEach((v) => {
          v.sensor.forEach((m) => {
            if (nodeId && m.id && nodeId.indexOf(m.id) != -1) m.checked = true;
            else m.checked = false;
          });
        });
      });
    },
    taskCancel() {
      this.dragSortDdata.forEach((ele) => {
        ele.select = false;
      });
      this.dealwithSensor();
      this.$emit("close", false);
    },
    taskOk() {
      let _this = this;
      this.$refs["formCustom"].validate((valid) => {
        if (valid) {
          let queryParam = _this.formListData(); //需要在此基础进行改造

          let param = {};
          param.sourceId = 1; //1表示周期任务 0表示推送
          param.taskName = _this.formData.taskName;
          param.crontabExpress = _this.formData.frequence;

          let taskParameter = {};
          taskParameter.queryParam = queryParam;
          taskParameter.beginTime = _this.formData.taskStartTime;
          taskParameter.endTime = _this.formData.taskEndTime;
          taskParameter.productType = _this.formData.productType;
          taskParameter.processDir = _this.formData.outputPath;
          // 用于编辑行政区域界面回显
          taskParameter.areaInfo = this.dealwithAreaInfo();
          param.taskParameter = JSON.stringify(taskParameter);

          _this.$emit("ok", param);

          this.dealwithSensor();
          this.dragSortDdata.forEach((ele) => {
            ele.select = false;
          });
        } else {
          _this.$Message.warning("请完整填写表单");
        }
      });
    },
    // 提交时保存当前界面的区域范围条件的信息 用于界面回显
    dealwithAreaInfo() {
      let areaInfo = {};
      if (this.tabValue === "a") {
        areaInfo = {
          tag: this.tabValue,
          value: this.selectCity.city,
        };
      } else if (this.tabValue === "b") {
        areaInfo = {
          tag: this.tabValue,
          value: this.reserveCity,
        };
      } else {
        areaInfo = { tag: this.tabValue, value: "" };
      }
      return areaInfo;
    },
    //获取生产类型
    getTaskTypeList() {
      let path = this.$api.manageApi.getAllChildByDictCode;
      let param = { dictCode: "productType" };
      this.taskTypeList = [];

      this.http.get(path, param).then((res) => {
        if (res.data.success) {
          let content = res.data.data;

          for (let i = 0; i < content.dictCodeList.length; i++) {
            let tempParam = {
              value: content.dictCodeList[i].dictCode,
              label: content.dictCodeList[i].dictName,
            };
            this.taskTypeList.push(tempParam);
          }
        }
      });
    },

    formListData() {
      let that = this;
      let formList = {};
      let string = "";
      this.selectSenior.forEach((item) => {
        string = string + item + ",";
      });

      this.formDataList[0].value[0] = that.formData.startTime
        ? this.$moment(that.formData.startTime).format("YYYY-MM-DD")
        : "";
      this.formDataList[0].value[1] = that.formData.endTime
        ? this.$moment(that.formData.endTime).format("YYYY-MM-DD")
        : "";
      this.formData.taskStartTime = this.formDataList[0].value[0];
      this.formData.taskEndTime = this.formDataList[0].value[1];

      this.formDataList[1].value = this.formData.cloudiness;
      // this.formDataList[2].value = this.formData.resolvingPower;

      if (this.tabValue === "a") {
        formList.areaCode =
          this.selectCity.city[this.selectCity.city.length - 1];
      } else if (this.tabValue === "b") {
        // let data = JSON.parse(JSON.stringify(this.reserveCity.name));
        // formList.areaCode = data.join(",");
        formList.areaCode = this.reserveCity.name;
      } else if (this.tabValue === "c") {
        formList.wkt = `POLYGON((${this.latitudeLongitude.leftTopLat} ${this.latitudeLongitude.leftTopLong},${this.latitudeLongitude.leftTopLat} ${this.latitudeLongitude.rightBottomLong},${this.latitudeLongitude.rightBottomLat} ${this.latitudeLongitude.rightBottomLong},${this.latitudeLongitude.rightBottomLat} ${this.latitudeLongitude.leftTopLong},${this.latitudeLongitude.leftTopLat} ${this.latitudeLongitude.leftTopLong}))`;
      } else if (this.tabValue === "d") {
        formList.wkt = that.updateWkt;
      }
      let dragSortDdataArr = JSON.parse(JSON.stringify(this.dragSortDdata));
      formList.optimalRules = dragSortDdataArr.filter((item) => {
        if (item.select) return true;
      });

      formList.nodeId = string;
      formList.fields = this.formDataList;
      formList.queryType = 0; //0表示查询原始数据 1表示产品数据  2原始+产品数据

      return formList;
    },
    //点击卫星添加卫星下的所有
    changeSing(data, list) {
      if (data) {
        this.$set(list, "checked", true);
        list.sensor.forEach((item) => {
          this.$set(item, "checked", true);
          this.selectSenior.add(item.id);
        });
      } else {
        this.$set(list, "checked", false);
        list.sensor.forEach((item) => {
          this.$set(item, "checked", false);
          this.selectSenior.delete(item.id);
        });
      }
    },
    // 点击单个向set中添加对象
    changeChe(data, list, parentList) {
      if (data) {
        this.$set(list, "checked", true);
        this.selectSenior.add(list.id);
        this.changeSingStatus(parentList);
      } else {
        this.$set(list, "checked", false);
        this.selectSenior.delete(list.id);
        this.changeSingStatus(parentList);
      }
    },
    changeSingStatus(list) {
      let length = list.sensor.filter((ele) => !ele.checked).length;
      if (length == list.sensor.length && list.checked) {
        this.$set(list, "checked", false);
      }
      let length1 = list.sensor.filter((ele) => ele.checked).length;
      if (length1 == list.sensor.length && !list.checked) {
        this.$set(list, "checked", true);
      }
    },

    /**区域获取 start */
    loadData(item, callback) {
      item.loading = true;
      if (item.__value) {
        let data = item.__value.split(",").length;
        if (data === 1) {
          this.getQueryArea(1, item.code, item, callback);
        }
        if (data === 2) {
          this.getQueryArea(2, item.code, item, callback);
        }
      }
    },
    handleChangePreRegion(value, selectedData) {
      this.handleChangeCity([value], selectedData);
    },
    handleChangeCity(value, selectedData) {
      return;
      let path = this.$api.dataOptimizationApi.getAreaGeometry;
      let param = {
        code: value[value.length - 1],
      };
      this.http.get(path, param).then((res) => {
        if (res.data.success) {
          // let geometry = res.data.data.geom;
          // this.drawGeometry(geometry);
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    // 获取行政区域
    getQueryArea(type = 0, code = null, itemList, callback) {
      let that = this;
      let formdata = new FormData();
      formdata.set("type", type);
      formdata.set("code", code);
      this.http
        .post(this.$api.dataOptimizationApi.queryArea, formdata)
        .then((res) => {
          if (res.data.success) {
            if (res.data.data.data.length < 1) {
              itemList.loading = false;
              this.handleChangeCity([itemList.value]); //没有子节点，则查自身的范围
              return;
            } else {
              res.data.data.data.forEach((item) => {
                item.label = item.name;
                item.value = item.code;
                if (type !== 2) {
                  item.children = [];
                  item.loading = false;
                }

                if (item.code === "000000") {
                  // 保证数据联机的三级完整
                  item.children = [
                    {
                      children: [],
                      code: "000000",
                      label: "全国",
                      loading: false,
                      name: "全国",
                      value: "000000",
                      __label: "全国",
                      __value: "000000",
                    },
                  ];
                }
                if (item.code === "810000") {
                  // 保证数据联机的三级完整
                  item.children = [
                    {
                      children: [],
                      __label: "香港特别行政区",
                      __value: "810000",
                      code: "810000",
                      label: "香港特别行政区",
                      loading: false,
                      name: "香港特别行政区",
                      value: "810000",
                    },
                  ];
                }
                if (item.code === "820000") {
                  // 保证数据联机的三级完整
                  item.children = [
                    {
                      children: [],
                      __label: "澳门特别行政区",
                      __value: "820000",
                      code: "820000",
                      label: "澳门特别行政区",
                      loading: false,
                      name: "澳门特别行政区",
                      value: "820000",
                    },
                  ];
                }
              });
            }

            if (itemList) {
              itemList.loading = false;
              itemList.children = res.data.data.data;
              if (callback) {
                callback();
              }
            } else {
              that.cityData = res.data.data.data;
            }
          } else {
            this.$Message.error(res.data.message);
          }
        });
    },
    onError() {
      this.$Message.info("上传失败!");
    },
    onSuccess(response, file, fileList) {},
  },
};
</script>
<style  scoped>
/deep/.ivu-modal-body {
  height: calc(70vh);
  overflow-y: auto;
}
/deep/.ivu-collapse-header {
  display: flex;
  align-items: center;
}
/deep/ .ivu-form-item {
  margin-bottom: 0;
}
/deep/.ivu-date-picker {
  width: 100%;
}

/* /deep/.outpath .ivu-form-item-content {
  display: flex;
} */
/deep/.selectOp {
  display: flex;
}
.selectOp div {
  width: 100px;
}
/deep/.ivu-form-item-error-tip {
  padding-top: 0;
}

/deep/.rowAlign,
.rowAlign1 {
  display: flex;
}
/deep/.rowAlign1 .ivu-form-item-content {
  width: 212px;
  display: flex;
}

/deep/.rowAlign .ivu-form-item-content {
  width: 212px;
}
</style>